package com.siysoft.tc.reservation.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.siysoft.tc.base.bean.bo.AvatarBo;
import com.siysoft.tc.base.bean.bo.MessageBo;
import com.siysoft.tc.base.bean.bo.PTDetailBo;
import com.siysoft.tc.base.bean.bo.PaginationBo;
import com.siysoft.tc.base.bean.bo.ReservationBo;
import com.siysoft.tc.base.bean.bo.StudentEvaluationTotalBo;
import com.siysoft.tc.base.bean.bo.TeacherEvaluationBo;
import com.siysoft.tc.base.bean.bo.TeacherEvaluationTotalBo;
import com.siysoft.tc.base.bean.property.ResourceType;
import com.siysoft.tc.base.bean.to.EvaluateStudent;
import com.siysoft.tc.base.bean.to.EvaluateTeacher;
import com.siysoft.tc.base.bean.to.Friend;
import com.siysoft.tc.base.bean.to.MsgArticle;
import com.siysoft.tc.base.bean.to.MsgArticleToRead;
import com.siysoft.tc.base.bean.to.Order;
import com.siysoft.tc.base.bean.to.Reservation;
import com.siysoft.tc.base.bean.to.Resource;
import com.siysoft.tc.base.bean.to.User;
import com.siysoft.tc.base.bean.to.UserReservation;
import com.siysoft.tc.base.bean.to.VUserReservation;
import com.siysoft.tc.reservation.service.IReservationService;
import com.siysoft.util.COMMON;
import com.tc.base.dao.BaseDAO;

@Service
public class ReservationServiceImpl implements IReservationService{
	@Autowired
	BaseDAO baseDao;
	
	public String getResource(int data_id, String type) {
		String hql= "from Resource a where a.dataType='"+type+"' AND a.dataId="+data_id;
		List<Resource> resourcelist =baseDao.findByHQL(hql);
		Resource resource1=new Resource();
		if(resourcelist.size()!=0){
			return resourcelist.get(0).getImgPath();
		}
		return null;
		
	}

	@Override
	public List<ReservationBo> getAll(Integer id, String school) {
		// TODO Auto-generated method stub
		//String hql = "from Reservation where reservation_status<5 and reservation_school='"+school+"' and reservation_ispublic=0";
		String hql = "from Reservation where reservation_school='"+school+"' and reservation_ispublic=0 order by reservation_recommend_index desc";
		List<Reservation> reservation = baseDao.findByHQL(hql);
		List<ReservationBo> reservation_bo = new ArrayList<ReservationBo>();
		for(Integer i = 0; i < reservation.size(); i++){
			Reservation r = reservation.get(i);
			int reservation_id = r.getReservation_id();
			String reservation_number = r.getReservation_number();
			Integer reservation_state = r.getReservation_status();
			Integer reservation_ispublic = r.getReservation_ispublic();
			String reservation_course = r.getReservation_course();
			Timestamp reservation_time = r.getReservation_time();
			String reservation_address = r.getReservation_address();
			String hql1 = "from UserReservation where user_id="+id+" and reservation_id="+r.getReservation_id();
			List<UserReservation> ur = baseDao.findByHQL(hql1);
			Integer user_reservation_status = -1;
			if(ur.size() > 0){
				user_reservation_status = ur.get(0).getUser_reservation_status();
			}
			ReservationBo rb = new ReservationBo(reservation_id, reservation_number, 
					reservation_state, reservation_ispublic, reservation_course, 
					reservation_time, reservation_address, user_reservation_status);
			reservation_bo.add(rb);
		}
		return reservation_bo;
	}
	
	@Override
	public String pay(Integer user_id, Integer reservation_id) {
		// TODO Auto-generated method stub
		String hql = "from Order where user_id=" + user_id + " and reservation_id=" + reservation_id;
		List<Order> order = baseDao.findByHQL(hql);
		if(order.size() > 0){
			return "请勿重复提交订单！";
		}
		else{
			
			double price = 0.0;
			String title = "";
			
			//补课金额
			Reservation r = (Reservation) baseDao.findById(Reservation.class, reservation_id);
			if(r.getReservation_wage() > 0){
				title += "补课金额：" + r.getReservation_wage() + "£|";
				price += r.getReservation_wage();
			}
			
			//如果是首单，五磅提成
			Integer teacher_id = r.getReservation_lecture_id();
			String hql1 = "from VUserReservation where user_id=" + user_id + " and reservation_lecture_id=" + teacher_id + " and user_reservation_status>=2";
			List<VUserReservation> lvur = baseDao.findByHQL(hql1);
			if(COMMON.isEmpty(lvur.size())){
				title += "老师首单提成：5£|";
				price += 5;
			}
			
			//管理员协助提成
			if(r.getReservation_administrator() == 1){
				title += "管理员协助提成：" + r.getReservation_wage()*0.2 + "£|";
				price += r.getReservation_wage()*0.2;
			}
			
			//bonus
			if(r.getReservation_bonus() > 0){
				title += "Bonus：" + r.getReservation_bonus() + "£|";
				price += r.getReservation_bonus();
			}
			
			title += "总价格为：" + price + "£";
			
			Order o = new Order();
			o.setUser_id(user_id);
			o.setReservation_id(reservation_id);
			o.setOrder_price(price);
			o.setOrder_title(title);
			Timestamp d = new Timestamp(System.currentTimeMillis()); 
			o.setOrder_cdate(d);
			o.setOrder_status(0);
			baseDao.save(o);
			
			return title;
		}
	}

	@Override
	public List<MessageBo> getClassroom(String number, PaginationBo pb) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Integer reply(Integer id, String number, String message) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String state(Integer id, String number, Integer state) {
		// TODO Auto-generated method stub
		String hql = "from Reservation where reservation_create_id="+id+" and reservation_number='"+number+"'";
		List<Reservation> reservation = baseDao.findByHQL(hql);
		String hql2 = "from Reservation where reservation_number='"+number+"'";
		List<Reservation> tmp_reservation = baseDao.findByHQL(hql2);
		if(tmp_reservation.size() == 0){
			return "无此订单单号";
		}
		if(reservation.size() == 0){
			return "该用户不是订单创建者";
		}
		else{
			Reservation r = reservation.get(0);
			if(r.getReservation_status() != state-1){
				if(state == 3){
					return "还有人未支付订单";
				}
				else if(state == 4){
					return "订单还未开始";
				}
				else{
					return "状态错误";
				}
			}
			else{
				r.setReservation_status(state);
				baseDao.update(r);
				return "修改成功";
			}
		}
	}

	@Override
	public String getTeacherAvatar(Integer reservation_id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String evaluateStudent(Integer student_id, Integer reservation_id,
			Integer patience, Integer professionalism, Integer expression,
			Integer usefulness, Integer interaction, String detail,
			Integer isgoal) {
		// TODO Auto-generated method stub
		String hql = "from EvaluateStudent where evaluate_user_id="+student_id+" and evaluate_reservation_id="+reservation_id;
		List<EvaluateStudent> les = baseDao.findByHQL(hql);
		if(les.size() > 0){
			return "You hava evaluated!";
		}
		else{
			EvaluateStudent es = new EvaluateStudent();
			es.setEvaluate_user_id(student_id);
			es.setEvaluate_reservation_id(reservation_id);
			es.setEvaluate_patience(patience);
			es.setEvaluate_professionalism(professionalism);
			es.setEvaluate_expression(expression);
			es.setEvaluate_usefulness(usefulness);
			es.setEvaluate_interaction(interaction);
			es.setEvaluate_content(detail);
			es.setEvaluate_isgoal(isgoal);
			es.setEvaluate_time(new Timestamp(System.currentTimeMillis()));
			Reservation tmp_r = (Reservation) baseDao.findById(Reservation.class, reservation_id);
			es.setEvaluate_teacher_id(tmp_r.getReservation_lecture_id());
			baseDao.save(es);
			
			String hql1 = "from UserReservation where user_id="+student_id+" and reservation_id="+reservation_id;
			List<UserReservation> lur = baseDao.findByHQL(hql1);
			lur.get(0).setUser_reservation_status(5);
			baseDao.save(lur.get(0));
			
			//判断是否所有人均已完成评价
			judgeAllEvaluate(reservation_id);
			
			return "Success for evaluate!";
		}
	}

	@Override
	public Integer goal(Integer id, String number, Integer goal) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<AvatarBo> getstudent(Integer reservation_id, PaginationBo pb) {
		// TODO Auto-generated method stub
		try{
			String hql = "from VUserReservation where reservation_id="+reservation_id;
			List<VUserReservation> lvur = (List<VUserReservation>)baseDao.findByHQL(hql, null, pb.getPagination_offset(), pb.getPagination_limit());
			pb.setPagination_total(baseDao.findByHQL(hql).size());
			List<AvatarBo> lab = new ArrayList<AvatarBo>();
			for(Integer i = 0; i < lvur.size(); i++){
				VUserReservation vur = lvur.get(i);
				if(vur.getUser_type() == 0){
					int avatar_user_id = vur.getUser_id();
					String avatar_url = COMMON.NulltoAvatar(this.getResource(avatar_user_id,ResourceType.USER_AVATAR));
					String avatar_name = ((User)baseDao.findById(User.class, avatar_user_id)).getUser_name();
					AvatarBo ab = new AvatarBo(avatar_user_id, avatar_url,avatar_name);
					lab.add(ab);
				}
			}
			return lab;
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public void judgeAllEvaluate(int reservation_id){
		//判断是否所有人均已完成评价
		String hql2 = "from UserReservation where reservation_id="+reservation_id;
		List<UserReservation> lurs = baseDao.findByHQL(hql2);
		Integer flag = 0;
		for (UserReservation userReservation : lurs) {
			if(userReservation.getUser_reservation_status() != 5){
				flag = 1;
				break;
			}
		}
		if(flag == 0){
			String hql3 = "from Reservation where reservation_id="+reservation_id;
			List<Reservation> lr = baseDao.findByHQL(hql3);
			lr.get(0).setReservation_status(5);
			baseDao.update(lr.get(0));
		}
	}

	@Override
	public Integer evaluateTeacher(Integer teacher_id, Integer reservation_id, JSONArray evaluation) {
		// TODO Auto-generated method stub
		for(Integer i = 0; i < evaluation.size(); i++){
			JSONObject tmp_evaluation = (JSONObject)evaluation.get(i);
			EvaluateTeacher evaluate_teacher = new EvaluateTeacher();
			evaluate_teacher.setEvaluate_reservation_id(reservation_id);
			evaluate_teacher.setEvaluate_teacher_id(teacher_id);
			evaluate_teacher.setEvaluate_student_id(Integer.valueOf(tmp_evaluation.get("student_id").toString()));
			evaluate_teacher.setEvaluate_content(tmp_evaluation.get("content").toString());
			evaluate_teacher.setEvaluate_up(Integer.valueOf(tmp_evaluation.get("up").toString()));
			evaluate_teacher.setEvaluate_down(Integer.valueOf(tmp_evaluation.get("down").toString()));
			evaluate_teacher.setEvaluate_time(new Timestamp(System.currentTimeMillis()));
			baseDao.save(evaluate_teacher);
			
			//更新User表中对应up/down的总个数
			Integer student_id = Integer.valueOf(tmp_evaluation.get("student_id").toString());
			User u = (User)baseDao.findById(User.class, student_id);
			if(Integer.valueOf(tmp_evaluation.get("up").toString()) == 1)
				u.setUser_up(u.getUser_up()+1);
			if(Integer.valueOf(tmp_evaluation.get("down").toString()) == 1)
				u.setUser_down(u.getUser_down()+1);
			baseDao.update(u);
			
		}
		String hql = "from UserReservation where user_id="+teacher_id+" and reservation_id="+reservation_id;
		List<UserReservation> ur = baseDao.findByHQL(hql);
		ur.get(0).setUser_reservation_status(5);
		baseDao.update(ur.get(0));
		
		//判断是否所有人均已完成评价
		judgeAllEvaluate(reservation_id);
		return 1;
	}

	@Override
	public PTDetailBo getTotalEvaluation(String number) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Integer apply(Integer id, String user_name, String reservation_number,
			String school, String lecture,
			String course, Integer max_size, String address, Timestamp time,
			Integer period, Integer goal, Integer wage, Integer bonus,
			Integer ispublic, Integer administrator) {
		// TODO Auto-generated method stub
		Timestamp now_time = new Timestamp(System.currentTimeMillis());
		//预约单创建时间不能早于现在
		if(now_time.after(time)){
			return 0;
		}
		Reservation re = new Reservation();
		int lecture_id = -1;
		if(!lecture.isEmpty()){
			String hql = "from User where user_name='"+lecture+"'";
			List<User> lu = baseDao.findByHQL(hql);
			lecture_id = lu.get(0).getUser_id();
		}
		re.setReservation_lecture_id(lecture_id);
		re.setReservation_create_id(id);
		re.setReservation_number(reservation_number);
		re.setReservation_school(school);
		re.setReservation_course(course);
		re.setReservation_max_size(max_size);
		re.setReservation_current_size(0);
		re.setReservation_address(address);
		re.setReservation_time(time);
		re.setReservation_period(period);
		re.setReservation_goal(goal);
		re.setReservation_wage(wage);
		re.setReservation_bonus(bonus);
		re.setReservation_ispublic(ispublic);
		re.setReservation_administrator(administrator);
		re.setReservation_status(0);
		re.setReservation_recommend_index(0);
		Integer reservation_id = (Integer) baseDao.saveReturnId(re);
		
		this.creator_join(id, reservation_id);
		
		if(!lecture.isEmpty()){
			this.join(lecture_id, reservation_id, wage, period);
		}
		
		return 1;
	}
	
	@Override
	public Integer update(Integer reservation_id, String school,
			String lecture, Integer max_size, String address, Timestamp time,
			Integer period, Integer goal, Integer wage, Integer bonus) {
		// TODO Auto-generated method stub
		Reservation r = (Reservation)baseDao.findById(Reservation.class, reservation_id);
		if(r.getReservation_current_size() > max_size){
			//最大人数小于当前人数
			return -1;
		}
		else{
			if(!lecture.isEmpty()){
				String hql = "from User where user_name='"+lecture+"'";
				List<User> lu = baseDao.findByHQL(hql);
				if(COMMON.isEmpty(lu)){
					//老师不存在
					return -2;
				}
				else{
					Integer tmp_current_size = r.getReservation_current_size();
					//移除老师，加入新的老师
					String hql5 = "from UserReservation where user_id="+r.getReservation_lecture_id()+" and reservation_id="+reservation_id;
					List<UserReservation> tmp_lur = baseDao.findByHQL(hql5);
					if(tmp_lur.size() > 0){
						baseDao.delete(tmp_lur.get(0));
						tmp_current_size = tmp_current_size - 1;
					}
					UserReservation ur = new UserReservation();
					ur.setReservation_id(reservation_id);
					ur.setUser_id(lu.get(0).getUser_id());
					ur.setUser_reservation_status(0);
					baseDao.save(ur);
					
					r.setReservation_current_size(tmp_current_size+1);
					r.setReservation_lecture_id(lu.get(0).getUser_id());
					r.setReservation_school(school);
					r.setReservation_max_size(max_size);
					r.setReservation_address(address);
					r.setReservation_time(time);
					r.setReservation_period(period);
					r.setReservation_goal(goal);
					r.setReservation_wage(wage);
					r.setReservation_bonus(bonus);
					baseDao.update(r);
					
					//将所有成员状态变为0
					String hql1 = "from UserReservation where reservation_id="+reservation_id;
					List<UserReservation> lur = baseDao.findByHQL(hql1);
					for(Integer i = 0; i < lur.size(); i++){
						if(lur.get(i).getUser_id() == r.getReservation_create_id()){
							continue;
						}
						lur.get(i).setUser_reservation_status(0);
						baseDao.update(lur.get(i));
					}
					return 1;
				}
			}
			else{
				//如果原来有老师，则移除老师
				String hql5 = "from UserReservation where user_id="+r.getReservation_lecture_id()+" and reservation_id="+reservation_id;
				List<UserReservation> tmp_lur = baseDao.findByHQL(hql5);
				if(tmp_lur.size() > 0){
					baseDao.delete(tmp_lur.get(0));
					r.setReservation_current_size(r.getReservation_current_size()-1);
				}
				r.setReservation_lecture_id(-1);
				r.setReservation_school(school);
				r.setReservation_max_size(max_size);
				r.setReservation_address(address);
				r.setReservation_time(time);
				r.setReservation_period(period);
				r.setReservation_goal(goal);
				r.setReservation_wage(wage);
				r.setReservation_bonus(bonus);
				baseDao.update(r);
				
				//将所有成员状态变为0
				String hql1 = "from UserReservation where reservation_id="+reservation_id;
				List<UserReservation> lur = baseDao.findByHQL(hql1);
				for(Integer i = 0; i < lur.size(); i++){
					if(lur.get(i).getUser_id() == r.getReservation_create_id()){
						continue;
					}
					lur.get(i).setUser_reservation_status(0);
					baseDao.update(lur.get(i));
				}
				return 1;
			}
		}
	}

	@Override
	public String join(Integer user_id, Integer reservation_id, Integer wage, Integer period) {
		// TODO Auto-generated method stub
		String hql = "from Reservation where reservation_id="+reservation_id;
		List<Reservation> r = baseDao.findByHQL(hql);
		
		//已经过了开始时间,则不能加入
		Timestamp now_time = new Timestamp(System.currentTimeMillis());
		Timestamp reservation_time = r.get(0).getReservation_time();
		if(reservation_time != null && now_time.after(reservation_time)){
			return "It's too late, you can not join the reservation!";
		}
		
		if(r.size() == 0){
			return "The reservation does not exist!";
		}
		else{
			Integer current_size = r.get(0).getReservation_current_size();
			if(r.get(0).getReservation_max_size() == current_size)
			{
				return "Toll to limit!";
			}
			else{
				String hql1 = "from UserReservation where user_id="+user_id+" and reservation_id="+reservation_id;
				List<UserReservation> lur = baseDao.findByHQL(hql1);
				if(lur.size() > 0){
					return "The person has joined!";
				}
				else{
					r.get(0).setReservation_current_size(current_size+1);
					baseDao.save(r.get(0));
					
					UserReservation ur = new UserReservation();
					ur.setUser_id(user_id);
					ur.setReservation_id(reservation_id);
					ur.setUser_reservation_status(0);
					ur.setUser_reservation_wage(wage);
					ur.setUser_reservation_period(period);
					baseDao.save(ur);
					
					//如果人数多于两人,创建者默认同意
					Integer creater_id = r.get(0).getReservation_create_id();
					String hql2 = "from UserReservation where user_id="+creater_id+" and reservation_id="+reservation_id;
					List<UserReservation> c_lur = baseDao.findByHQL(hql2);
					if(c_lur.get(0).getUser_reservation_status() == 0){
						c_lur.get(0).setUser_reservation_status(1);
						baseDao.update(c_lur.get(0));
					}
					
					return "Success for join!";
				}
			}
		}
	}
	
	public String creator_join(Integer user_id, Integer reservation_id) {
		// TODO Auto-generated method stub
		String hql = "from Reservation where reservation_id="+reservation_id;
		List<Reservation> r = baseDao.findByHQL(hql);
		if(r.size() == 0){
			return "The reservation does not exist!";
		}
		else{
			Integer current_size = r.get(0).getReservation_current_size();
			if(r.get(0).getReservation_max_size() == current_size)
			{
				return "Toll to limit!";
			}
			else{
				String hql1 = "from UserReservation where user_id="+user_id+" and reservation_id="+reservation_id;
				List<UserReservation> lur = baseDao.findByHQL(hql1);
				if(lur.size() > 0){
					return "The person has joined!";
				}
				else{
					r.get(0).setReservation_current_size(current_size+1);
					baseDao.save(r.get(0));
					UserReservation ur = new UserReservation();
					ur.setUser_id(user_id);
					ur.setReservation_id(reservation_id);
					ur.setUser_reservation_status(1);
					ur.setUser_reservation_wage(-1);
					ur.setUser_reservation_period(-1);
					baseDao.save(ur);
					return "Success for join!";
				}
			}
		}
	}
	
	@Override
	public String agree(Integer user_id, Integer reservation_id) {
		
		//判断预约单是否有老师
		Reservation j_r = (Reservation) baseDao.findById(Reservation.class, reservation_id);
		if(j_r.getReservation_lecture_id() == -1){
			return "There is no lecture, can not agree!";
		}
		
		// TODO Auto-generated method stub
		String hql = "from UserReservation where user_id="+user_id+" and reservation_id="+reservation_id;
		List<UserReservation> ur = baseDao.findByHQL(hql);
		if(ur.get(0).getUser_reservation_status() == 1){
			return "You have agreed!";
		}
		ur.get(0).setUser_reservation_status(1);
		baseDao.update(ur.get(0));
		
		//如果所有人都同意，更新预约单自身状态
		//所有人都同意的逻辑：所有学生与被选中的老师都同意
		String hql1 = "from VUserReservation where reservation_id="+reservation_id+" order by user_id";
		List<VUserReservation> lvur = baseDao.findByHQL(hql1);
		Integer flag = 1;
		for(Integer i = 0; i < lvur.size(); i++){
			VUserReservation vur = lvur.get(i);
			if(vur.getUser_id() == user_id) continue;
			if(vur.getUser_type() == 1){
				if(vur.getUser_id() == vur.getReservation_lecture_id() && vur.getUser_reservation_status() == 0){
					flag = 0;
					break;
				}
			}
			else{
				if(vur.getUser_reservation_status() == 0){
					flag = 0;
					break;
				}
			}
		}
		if(flag == 1){
			j_r.setReservation_status(1);
			baseDao.update(j_r);
			
			String hql2 = "from UserReservation where reservation_id="+reservation_id+" order by user_id";
			List<UserReservation> lur = baseDao.findByHQL(hql2);
			for(Integer i = lur.size()-1; i >= 0; i--){
				UserReservation tmp_ur = lur.get(i);
				VUserReservation tmp_vur = lvur.get(i);
				if(tmp_vur.getUser_type() == 1){
					if(tmp_vur.getUser_id() != j_r.getReservation_lecture_id()){
						//移除所有其他老师
						baseDao.delete(tmp_ur);
					}
					else{
						//老师跳过支付阶段
						tmp_ur.setUser_reservation_status(2);
						baseDao.update(tmp_ur);
					}
				}
			}
			
		}
		return "Success for agree!";
	}

	@Override
	public String begin(Integer reservation_id) {
		// TODO Auto-generated method stub
		
		String hql = "from Reservation where reservation_id="+reservation_id;
		List<Reservation> r = baseDao.findByHQL(hql);
		
		//没到开始时间,不能开始预约单
		Timestamp now_time = new Timestamp(System.currentTimeMillis());
		Timestamp reservation_time = r.get(0).getReservation_time();
		if(reservation_time.after(now_time)){
			return "Not arrive at the start time, can not start!";
		}
		
		//检测是否所有人都已经支付
		String hql1 = "from UserReservation where reservation_id="+reservation_id;
		List<UserReservation> ur = baseDao.findByHQL(hql1);
		Integer flag = 0;
		for(Integer i = 0; i < ur.size(); i++){
			if(ur.get(i).getUser_reservation_status() < 2){
				flag = 1;
				break;
			}
		}
		if(flag == 1){
			return "Someone have not paid, can not start!";
		}
		
		r.get(0).setReservation_status(3);
		baseDao.update(r.get(0));
		for(Integer i = 0; i < ur.size(); i++){
			UserReservation tmp_ur = ur.get(i);
			tmp_ur.setUser_reservation_status(3);
		}
		
		//所有成员互相添加好友
		String hql_friend = "";
		for(Integer i = 0; i < ur.size(); i++){
			for(Integer j = i+1; j < ur.size(); j++){
				Integer user_id1 = ur.get(i).getUser_id();
				Integer user_id2 = ur.get(j).getUser_id();
				
				hql_friend = "from Friend where friend_head_id="+user_id1+" and friend_dependent_id="+user_id2;
				List<Friend> lf1 = baseDao.findByHQL(hql_friend);
				if(lf1.size() == 0){
					Friend f1 = new Friend();
					f1.setFriend_head_id(user_id1);
					f1.setFriend_dependent_id(user_id2);
					baseDao.save(f1);
				}
				
				hql_friend = "from Friend where friend_head_id="+user_id2+" and friend_dependent_id="+user_id1;
				List<Friend> lf2 = baseDao.findByHQL(hql_friend);
				if(lf2.size() == 0){
					Friend f2 = new Friend();
					f2.setFriend_head_id(user_id2);
					f2.setFriend_dependent_id(user_id1);
					baseDao.save(f2);
				}
			}
		}
		
		return "Success for begin!";
	}

	@Override
	public String finish(Integer reservation_id) {
		// TODO Auto-generated method stub
		String hql = "from Reservation where reservation_id="+reservation_id;
		List<Reservation> r = baseDao.findByHQL(hql);
		r.get(0).setReservation_status(4);
		baseDao.update(r.get(0));
		String hql1 = "from UserReservation where reservation_id="+reservation_id;
		List<UserReservation> ur = baseDao.findByHQL(hql1);
		for(Integer i = 0; i < ur.size(); i++){
			UserReservation tmp_ur = ur.get(i);
			tmp_ur.setUser_reservation_status(4);
		}
		return "Success for finish!";
	}
	
	@Override
	public String finish_evaluate(Integer user_id, Integer reservation_id) {
		// TODO Auto-generated method stub
		String hql1 = "from UserReservation where user_id="+user_id+" and reservation_id="+reservation_id;
		List<UserReservation> ur = baseDao.findByHQL(hql1);
		for(Integer i = 0; i < ur.size(); i++){
			UserReservation tmp_ur = ur.get(i);
			tmp_ur.setUser_reservation_status(5);
			
			//判断是否所有人都完成评价
			judgeAllEvaluate(reservation_id);
		}
		return "Success for finish evaluate!";
	}

	@Override
	public String drop_out(Integer user_id, Integer reservation_id) {
		// TODO Auto-generated method stub
		String hql = "from UserReservation where user_id="+user_id+" and reservation_id="+reservation_id;
		List<UserReservation> lur = baseDao.findByHQL(hql);
		if(lur.get(0).getUser_reservation_status() > 0){
			return "You have agreed!";
		}
		String hql1 = "from Reservation where reservation_id="+reservation_id;
		List<Reservation> r = baseDao.findByHQL(hql1);
		Integer current_size = r.get(0).getReservation_current_size();
		Integer creater_id = r.get(0).getReservation_create_id();
		r.get(0).setReservation_current_size(current_size-1);
		
		//房主退出
		if(lur.get(0).getUser_id() == r.get(0).getReservation_create_id()){		
			int cnt_teacher = 0;
			if(r.get(0).getReservation_lecture_id() != -1) cnt_teacher = 1;
			
			String hql5 = "from UserReservation where reservation_id="+reservation_id;
			List<UserReservation> lur5 = baseDao.findByHQL(hql5);
			//如果房间没有其余学生，则删除预约单
			if(current_size-cnt_teacher < 2){
				for(int i = 0; i < lur5.size(); i++){
					baseDao.delete(lur5.get(i));
				}
				baseDao.delete(r.get(0));
			}
			//如果房间有剩余学生，则转移给第一个加入的学生
			else{
				for(int i = 0; i < lur5.size(); i++){
					if(lur5.get(i).getUser_id() != r.get(0).getReservation_lecture_id()){
						r.get(0).setReservation_create_id(lur5.get(i).getUser_id());
						baseDao.update(r.get(0));
						break;
					}
				}
			}
		}
		else{
		
			baseDao.delete(lur.get(0));
			
			//如果老师退出,更新预约单老师id
			User u = (User) baseDao.findById(User.class, user_id);
			if(u.getUser_type() == 1){
				r.get(0).setReservation_lecture_id(-1);
			}
			
			baseDao.update(r.get(0));
			
			//如果房间人数小于3,有人退出,则创建者状态变为0
			if(current_size < 3){
				String hql2 = "from UserReservation where user_id="+creater_id+" and reservation_id="+reservation_id;
				List<UserReservation> c_lur = baseDao.findByHQL(hql2);
				c_lur.get(0).setUser_reservation_status(0);
				baseDao.update(c_lur.get(0));
			}
		}
		
		return "success for drop out!";
	}

	@Override
	public TeacherEvaluationTotalBo get_teacher_evaluation_total(Integer id) {
		// TODO Auto-generated method stub
		String hql = "from EvaluateStudent where evaluate_reservation_id="+id;
		List<EvaluateStudent> les = baseDao.findByHQL(hql);
		if(COMMON.isEmpty(les)){
			return null;
		}
		Integer average_patience = 0;
		Integer average_professionalism = 0;
		Integer average_expression = 0;
		Integer average_usefulness = 0;
		Integer average_interaction = 0;
		for(Integer i = 0; i < les.size(); i++){
			average_patience += les.get(i).getEvaluate_patience();
			average_professionalism += les.get(i).getEvaluate_professionalism();
			average_expression += les.get(i).getEvaluate_expression();
			average_usefulness += les.get(i).getEvaluate_usefulness();
			average_interaction += les.get(i).getEvaluate_interaction();
		}
		average_patience /= les.size();
		average_professionalism /= les.size();
		average_expression /= les.size();
		average_usefulness /= les.size();
		average_interaction /= les.size();
		List<TeacherEvaluationBo> lteb = new ArrayList<TeacherEvaluationBo>();
		for(Integer i = 0; i < les.size(); i++){
			EvaluateStudent es = les.get(i);
			int user_id = es.getEvaluate_user_id();
			Integer patience = es.getEvaluate_patience();
			Integer professionalism = es.getEvaluate_professionalism();
			Integer expression = es.getEvaluate_expression();
			Integer usefulness = es.getEvaluate_usefulness();
			Integer interaction = es.getEvaluate_interaction();
			String content = es.getEvaluate_content();
			String user_avatar = COMMON.NulltoAvatar(this.getResource(user_id,ResourceType.USER_AVATAR));;
			User u = (User)baseDao.findById(User.class, user_id);
			String user_name = u.getUser_name();
			TeacherEvaluationBo teb = new TeacherEvaluationBo(user_id, patience, 
					professionalism, expression, usefulness, 
					interaction, content, user_avatar, user_name);
			lteb.add(teb);
		}
		TeacherEvaluationTotalBo tetb = new TeacherEvaluationTotalBo(average_patience, 
				average_professionalism, average_expression, 
				average_usefulness, average_interaction, lteb);
		return tetb;
	}

	@Override
	public StudentEvaluationTotalBo get_student_evaluation_total(
			Integer user_id, Integer reservation_id) {
		String hql = "from EvaluateTeacher where evaluate_student_id="+user_id+" and evaluate_reservation_id="+reservation_id;
		List<EvaluateTeacher> let = baseDao.findByHQL(hql);
		if(let.size() != 0){
			EvaluateTeacher et = let.get(0);
			Integer student_id = et.getEvaluate_student_id();
			Integer teacher_id = et.getEvaluate_teacher_id();
			String teacher_avatar = COMMON.NulltoAvatar(this.getResource(teacher_id,ResourceType.USER_AVATAR));;
			String content = et.getEvaluate_content();
			Integer up = et.getEvaluate_up();
			Integer down = et.getEvaluate_down();
			StudentEvaluationTotalBo setb = new StudentEvaluationTotalBo(student_id, 
					teacher_avatar, content, up, down);
			return setb;
		}
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<ReservationBo> search(Integer user_id, String lecture,
			String course, String school) {
		// TODO Auto-generated method stub
		String hql = "from Reservation where reservation_status<5 and reservation_school='"+school+"'";
		if(!lecture.equals("")){
			hql += " and reservation_lecture='" + lecture + "'";
		}
		if(!course.equals("")){
			hql += " and reservation_course='" + course + "'";
		}
		hql += " order by reservation_recommend_index desc";
		List<Reservation> reservation = baseDao.findByHQL(hql);
		List<ReservationBo> reservation_bo = new ArrayList<ReservationBo>();
		for(Integer i = 0; i < reservation.size(); i++){
			Reservation r = reservation.get(i);
			int reservation_id = r.getReservation_id();
			String reservation_number = r.getReservation_number();
			Integer reservation_state = r.getReservation_status();
			Integer reservation_ispublic = r.getReservation_ispublic();
			String reservation_course = r.getReservation_course();
			Timestamp reservation_time = r.getReservation_time();
			String reservation_address = r.getReservation_address();
			String hql1 = "from UserReservation where user_id="+user_id+" and reservation_id="+r.getReservation_id();
			List<UserReservation> ur = baseDao.findByHQL(hql1);
			Integer user_reservation_status = -1;
			if(ur.size() > 0){
				user_reservation_status = ur.get(0).getUser_reservation_status();
			}
			ReservationBo rb = new ReservationBo(reservation_id, reservation_number, 
					reservation_state, reservation_ispublic, reservation_course, 
					reservation_time, reservation_address, user_reservation_status);
			reservation_bo.add(rb);
		}
		return reservation_bo;
	}

	@Override
	public List<ReservationBo> search2(Integer user_id, String select_str, String school) {
		// TODO Auto-generated method stub
		String[] select_items = select_str.split(",");
		System.out.println(select_items.length);
		//String hql = "from Reservation where reservation_status<5 and reservation_school='"+school+"'";
		String hql = "from Reservation where reservation_school='"+school+"' order by reservation_recommend_index desc";
		if(select_items.length > 0){
			if(!select_items[0].equals("")){
				hql += " and reservation_lecture='" + select_items[0] + "'";
			}
		}
		if(select_items.length > 1){
			if(!select_items[1].equals("")){
				hql += " and reservation_course='" + select_items[1] + "'";
			}
		}
		/*if(select_items.length > 2){
			if(!select_items[2].equals("")){
				hql += " and (";
				String[] department_items = select_items[2].split("#");
				for(Integer i = 0; i < department_items.length; i++){
					if(i > 0) hql += " or ";
					hql += "teacher_department='" + department_items[i] + "'";
				}
				hql += ")";
			}
		}*/
		/*if(select_items.length > 3){
			if(!select_items[3].equals("")){
				hql += " and (";
				String[] grade_items = select_items[3].split("#");
				for(Integer i = 0; i < grade_items.length; i++){
					if(i > 0) hql += " or ";
					hql += "user_grade='" + grade_items[i] + "'";
				}
				hql += ")";
			}
		}*/
		if(select_items.length > 4){
			if(!select_items[4].equals("")){
				hql += " and (";
				String[] goal_items = select_items[4].split("#");
				for(Integer i = 0; i < goal_items.length; i++){
					if(i > 0) hql += " or ";
					hql += "reservation_goal='" + goal_items[i] + "'";
				}
				hql += ")";
			}
		}
		List<Reservation> reservation = baseDao.findByHQL(hql);
		List<ReservationBo> reservation_bo = new ArrayList<ReservationBo>();
		for(Integer i = 0; i < reservation.size(); i++){
			Reservation r = reservation.get(i);
			int reservation_id = r.getReservation_id();
			String reservation_number = r.getReservation_number();
			Integer reservation_state = r.getReservation_status();
			Integer reservation_ispublic = r.getReservation_ispublic();
			String reservation_course = r.getReservation_course();
			Timestamp reservation_time = r.getReservation_time();
			String reservation_address = r.getReservation_address();
			String hql1 = "from UserReservation where user_id="+user_id+" and reservation_id="+r.getReservation_id();
			List<UserReservation> ur = baseDao.findByHQL(hql1);
			Integer user_reservation_status = -1;
			if(ur.size() > 0){
				user_reservation_status = ur.get(0).getUser_reservation_status();
			}
			ReservationBo rb = new ReservationBo(reservation_id, reservation_number, 
					reservation_state, reservation_ispublic, reservation_course, 
					reservation_time, reservation_address, user_reservation_status);
			reservation_bo.add(rb);
		}
		return reservation_bo;
	}

	@Override
	public Integer sendInvite(Integer user_id, String content) {
		// TODO Auto-generated method stub
		//type: 1:系统消息 2:课程消息 11.系统文章
		MsgArticle msg = new MsgArticle(content, content, "", 1, new Timestamp(System.currentTimeMillis()));
		Integer msg_id = (Integer) baseDao.saveReturnId(msg);
		MsgArticleToRead msg_to_read = new MsgArticleToRead(String.valueOf(msg_id), String.valueOf(user_id), "0");
		baseDao.save(msg_to_read);
		return 1;
	}

	

}
